import axios from 'axios'

import {
  getMenuList
} from "../api/menu";
import router from "../router";

var allmenulist = [];
const routerList = []

export {
  allmenulist
}

export function getChildrenPath(apiUrl) {
  //console.log(apiUrl)

  // var menus = getMenuList.data.data;
  // allmenulist = getMenuList.data.data;
  // menus.forEach(me => {
  //   setChild(me, routerList, '', '')
  // })
  // let rou = {
  //   path: '/index',
  //   name: 'index',
  //   component: () => import('@/views/layout/index'),
  //   children: routerList
  // }
  // router.addRoute(rou)

  axios
    .post(apiUrl)
    .then(response => {

      //console.log(1,apiUrl)


      var menus = response.data.data;
      allmenulist = response.data.data;

      console.log(allmenulist)
      menus.forEach((me) => {
        //console.log(me);
        setChild(me, routerList, "", '');
      });
      let rou = {
        path: "/index",
        name: "index",
        component: () => import("@/views/layout/index"),
        children: routerList,
      };
      router.addRoute(rou);
    })
    .catch((err) => {
      console.log(err);
    })
    .finally(() => {});

}

//递归算法，递归循环: 在方法内部调用方法本身的过程，可以得到一个无限层级的集合对象
function setChild(me, routerList, rootName, rootPath) {
  rootName = rootName + '/' + me.name
  rootPath = rootPath + '/' + me.path
  // console.log(rootName);
  // console.log(rootPath);
  if (me.children != null && me.children != [] && me.children.length > 0) {
    //如果有下层
    me.children.forEach(node => {
      setChild(node, routerList, rootName, rootPath)
    })
  }
  //没有下层则说明这是一个路由
  let rou = {
    name: rootName,
    path: rootPath,
    component: () => import('@/views' + rootPath) // 注意字母大小写 @/views/common/BaiduMap
  }
  // console.log(rou.path);
  routerList.push(rou)
}


// //动态获取菜单集合
// axios
// .get(apiUrl+'?userId='+id)
// .then((response) => {
//   var menus = response.data.Items;
//   menus.forEach((me) => {
//     setChild(me,  "", "");
//   });
//   let rou = {
//     path: "/index",
//     name: "index",
//     component: () => import("@/views/Main/Index"),
//     children: routerList,
//   };
//   console.info(rou)
//   router.addRoute(rou);
// })
// .catch((err) => {
//   console.log(err);
// })
// .finally(() => {}); 
